package com._23DesignPattern._structure._proxy.DynamicProxy;

import sun.misc.ProxyGenerator;

import java.io.FileOutputStream;
import java.lang.reflect.Proxy;

/**
 * @Author: huangya
 * @Date: 2019/3/10
 * @Description:
 */
public class Test001 {

    public static void main(String[] args) {
//        LogHandler logHandler = new LogHandler();
//        IPurchase iPurchase = (IPurchase)logHandler.newProxyInstance(new PurchaseImpl());
//        iPurchase.buy();


        IPurchase purchase2 = new PurchaseImpl2();
        LogHandler logHandler2 = new LogHandler(purchase2);
        //根据传入的目标对象信息生成具有对应buy方法的代理类
        IPurchase purchaseProxyObject2 = (IPurchase) Proxy.newProxyInstance(purchase2.getClass().getClassLoader(), purchase2.getClass().getInterfaces(), logHandler2);
        purchaseProxyObject2.buy();


        IPurchase purchase3 = new PurchaseImpl3();
        logHandler2 = new LogHandler(purchase3);
        IPurchase purchaseProxyObject3 = (IPurchase) Proxy.newProxyInstance(purchase3.getClass().getClassLoader(), purchase3.getClass().getInterfaces(), logHandler2);
        purchaseProxyObject3.buy();


    }

    public static void createProxyClassFile() {
        String name = "ProxySubject";
        byte[] data = ProxyGenerator.generateProxyClass( name, new Class[] { IPurchase.class } );
        try
        {
            FileOutputStream out = new FileOutputStream( name + ".class" );
            out.write( data );
            out.close();
        }
        catch( Exception e )
        {
            e.printStackTrace();
        }
    }

}
